<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Canvas 测试</title>
    <style>
        body {
            text-align: center;
        }

        canvas {
            background: #ddd;
        }
    </style>
</head>
<body>
<canvas id="c1" width="500" height="500"></canvas>
<script>
    let c1 = document.getElementById("c1");
    // 获取画笔
    let cas = c1.getContext("2d");
    let x = 0;
    let y = 0;
    let xDirection = 1; // 1 向右 -1 向左
    let yDirection = 1; // 1 向右 -1 向左
    // 左右移动的联系
    let timer = setInterval(function () {
        // 清空画布
        cas.clearRect(0, 0, 500, 500);
        x += 5 * xDirection;
        y += 5 * yDirection;
        if (x > 400) {
            xDirection = -1;
        } else if (x <=0) {
            xDirection = 1;
        }
        if (y > 400) {
            yDirection = -1;
        } else if (y <=0) {
            yDirection = 1;
        }
        cas.strokeRect(x, y, 100, 100);

    }, 50)
    // cas.strokeRect(400, 0, 100, 80);


</script>
</body>
</html>